package com.twetec.cms.service.website.impl;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.twetec.cms.common.util.validate.ValidateUtil;
import com.twetec.cms.dao.mapper.website.ArticleAttachmentMapper;
import com.twetec.cms.model.po.website.ArticleAttachmentPO;
import com.twetec.cms.model.vo.website.AttachmentVO;
import com.twetec.cms.service.website.ArticleAttachmentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 文章附件表 服务实现类
 * </p>
 *
 * @author zhxl
 * @since 2021-10-08
 */
@Service
public class ArticleAttachmentServiceImpl extends ServiceImpl<ArticleAttachmentMapper, ArticleAttachmentPO> implements ArticleAttachmentService {

    @Autowired
    private ArticleAttachmentMapper articleAttachmentMapper;
    @Override
    public boolean saveOrUpdateAttachment(Long articleId, String attachmentListJson, Long userId) {

        QueryWrapper<ArticleAttachmentPO> articleAttachmentPOQueryWrapper = new QueryWrapper<>();
        articleAttachmentPOQueryWrapper.eq("ARTICLE_ID", articleId);
        List<ArticleAttachmentPO> articleAttachmentPOList = articleAttachmentMapper.selectList(articleAttachmentPOQueryWrapper);

        // 1、如果查询到了数据就先删除
        ArrayList<Long> articleAttachList = new ArrayList<>();
        if (!ValidateUtil.isNullOrEmpty(articleAttachmentPOList)) {
            for (ArticleAttachmentPO articleAttachmentPO : articleAttachmentPOList) {
                articleAttachList.add(articleAttachmentPO.getId());
            }
            articleAttachmentMapper.deleteBatchIds(articleAttachList);
        }

        // 2、再遍历json对象，转换为对象之后再新增
        if (StringUtils.isNotEmpty(attachmentListJson)) {
            List<AttachmentVO> attachmentList = JSONArray.parseArray(attachmentListJson, AttachmentVO.class);
            for (AttachmentVO attachment : attachmentList) {
                ArticleAttachmentPO articleAttachmentPO = new ArticleAttachmentPO();
                articleAttachmentPO.setArticleId(articleId);
                articleAttachmentPO.setAttachmentName(attachment.getAttachmentName());
                articleAttachmentPO.setAttachmentUrl(attachment.getAttachmentUrl());
                articleAttachmentPO.setModifierId(userId);
                articleAttachmentPO.setCreatorId(userId);
                articleAttachmentMapper.insert(articleAttachmentPO);
            }
        }
        return true;
        // 报错就自然传回false
    }
}
